package com.example.function.integration.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.example.function.integration.config.CommonBeanConfig;
import com.example.function.integration.config.GlobalLocalCacheConfig;
import com.example.function.integration.service.ImportAndExportService;
import com.example.function.integration.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.example.function.integration.constant.CommonConstant.CSV;

/**
 * @Description: 导入导出服务接口实现类
 * @ClassName: ImportAndExportServiceImpl
 * @Author: ext.fengcheng
 * @Create: 2023-08-08 15:41
 */
@Service
public class ImportAndExportServiceImpl implements ImportAndExportService {

    @Resource
    private CommonBeanConfig commonBeanConfig;

    public static List<Object> sheetHead = Arrays.asList("姓名", "年龄", "性别", "电话", "城市", "邮编", "性别", "地址", "电子邮箱", "详细地址");

    public static Logger logger = LoggerFactory.getLogger(ImportAndExportServiceImpl.class);

    /**
     * @Description: 导入文件数据，解析文件，存入本地缓存
     * @ClassName: ImportAndExportServiceImpl
     * @Create: 2023/8/8 16:12
     * @Author: ext.fengcheng
     * @Params: [file]
     * @Returns: boolean
     */
    @Override
    public boolean importFileData(MultipartFile file) {
        String remark = "ImportAndExportServiceImpl.importUserData.";
        logger.info("{}开始解析文件数据并转成Json数组", remark);
        JSONArray array;
        try {
            // 开始解析文件
            array = ExcelUtils.readExcelToJsonArray(file, 1);
            if (!CollectionUtils.isEmpty(array)) {
                JSONArray jsonArray = (JSONArray) GlobalLocalCacheConfig.get("user");
                if (!CollectionUtils.isEmpty(jsonArray)) {
                    jsonArray.addAll(array);
                    GlobalLocalCacheConfig.put("user", jsonArray);
                } else {
                    GlobalLocalCacheConfig.put("user", array);
                }
                logger.info("{}解析文件数据成功，并且已存入本地缓存", remark);
            } else {
                logger.info("{}文件数据为空", remark);
            }
            return true;
        } catch (Exception e) {
            logger.error("{}解析导入文件数据发生异常，异常信息：{}", remark, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 导出数据，生成文件到本地
     * @ClassName: ImportAndExportServiceImpl
     * @Create: 2023/8/8 18:05
     * @Author: ext.fengcheng
     * @Params: [fileName, response]
     * @Returns: boolean
     */
    @Override
    public boolean exportFileData(String fileName, HttpServletResponse response) {
        String remark = "ImportAndExportServiceImpl.exportFileData.";
        logger.info("{}开始处理导出文件数据并生成文件到本地,开始执行时间：{}", remark, DateUtils.toString(new Date()));
        // 第 1 个 Sheet 页
        List<List<Object>> sheet1 = new ArrayList<>();
        sheet1.add(sheetHead);
        getUserSheelData(sheet1);

        // 第 2 个 Sheet 页
        List<List<Object>> sheet2 = new ArrayList<>();
        sheet2.add(sheetHead);
        getUserSheelData(sheet2);

        // 第 3 个 Sheet 页
        List<List<Object>> sheet3 = new ArrayList<>();
        sheet3.add(sheetHead);
        getUserSheelData(sheet3);

        // 第 4 个 Sheet 页
        List<List<Object>> sheet4 = new ArrayList<>();
        sheet4.add(sheetHead);
        getUserSheelData(sheet4);

        // 第 5 个 Sheet 页
        List<List<Object>> sheet5 = new ArrayList<>();
        sheet5.add(sheetHead);
        getUserSheelData(sheet5);

        // 将多个 Sheet 页添加到集合中
        Map<String, List<List<Object>>> sheets = new LinkedHashMap<>();
        sheets.put("第1批用户", sheet1);

        try {
            // 导出数据exportManySheet公共方法第一个参数如果传null，则导出文件到本地，目录是：D:\测试导入导出
            // exportManySheet公共方法第一个参数如果传response对象，则由前端页面进行导出文件，
            ExcelUtils.exportManySheet(fileName + CSV, true, commonBeanConfig.getThreadPollObj(), sheets, response);
            logger.info("{}导出文件数据，执行完成,执行结束时间：{}", remark, DateUtils.toString(new Date()));
        } catch (Exception e) {
            logger.error("{}导出文件数据发生异常，异常信息：{}", remark, e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return true;
    }

    private static void getUserSheelData(List<List<Object>> sheetData) {
        JSONArray array = JSONObject.parseObject(GlobalLocalCacheConfig.get("user").toString(), JSONArray.class);
        for (Object obj : array) {
            List<Object> rowData = new ArrayList<>();
            rowData.add(((JSONObject) obj).get("姓名"));
            rowData.add(((JSONObject) obj).get("电话"));
            rowData.add(((JSONObject) obj).get("邮编"));
            rowData.add(((JSONObject) obj).get("地址"));
            rowData.add(((JSONObject) obj).get("年龄"));
            rowData.add(((JSONObject) obj).get("城市"));
            rowData.add(((JSONObject) obj).get("电子邮箱"));
            rowData.add(((JSONObject) obj).get("详细地址"));
            rowData.add(((JSONObject) obj).get("性别"));
            sheetData.add(rowData);
        }
    }
}
